﻿using System;
using System.Reflection;
using System.Web.UI;

using BizElements.BusinessLayer;

namespace BizElements.Web
{
    static class ControlPropertyBinderFactory
    {
        internal static IControlPropertyBinder CreateBindableControlProperty(IBoundControl control)
        {
            return CreateBindableControlProperty(control, control.TwoWayBoundProperty);
        }

        internal static IControlPropertyBinder CreateBindableControlProperty(IBoundControl control, string propertyName)
        {
            PropertyInfo controlProperty = control.GetType().GetProperty(propertyName);
            Type propertyType = controlProperty.PropertyType;
            if (TypeUtil.IsText(propertyType))
            {
                bool useDecimalParserForLookupControl = control is IBoundLookupControl;
                return new TextualPropertyBinder(useDecimalParserForLookupControl);
            }
            else if (controlProperty.PropertyType == typeof(bool))
            {
                return new BooleanPropertyBinder();
            }
            else if (controlProperty.PropertyType == typeof(DateTime?))
            {
                return new NullableDateTimePropertyBinder();
            }
            else
            {
                throw new InvalidOperationException("Unsupported control property data type. Property: '" + propertyName + "'. Type: " + propertyType.Name);
            }
        }
    }
}
